import { IModule } from "../common/Common";
import Utils from "../utils/Utils";
import { loadItem } from "./ResDefine";

/**资源管理 */
export default class ResManage implements IModule {

    static I: ResManage;

    private _assets = new Map<string, ResData>();

    constructor() {
        ResManage.I = this;
    }


    initialize(): void {
    }

    //删除未引用的资源
    public destroyUnusedResources() {
        Laya.Resource.destroyUnusedResources();
    }


    async load(url: string, type?: string) {
        let res = Laya.Loader.getRes(url, type);

        return Laya.loader.load(url, type);
    }

    /**
     * 异步获取资源
     * @param url 路径
     * @param type 类型
     */
    getRes(url: string, type?: string): Promise<any> {

        return new Promise((resolve) => {
            let res = this.getRes(url);
            if (res) {
                return resolve(res);
            }

            return Laya.loader.load(url, Laya.Handler.create(this, resolve, [this.getRes(url)]), null, type);
        })
    }

    clearRes(group: string) {
        let asset = this._assets.get(group)
        if (!asset) return;
        asset.clera();
        this._assets.delete(group);
    }
}

export class ResData {

    private assets: loadItem[];

    constructor(private group: string, private priority: number = 1) {

        this.assets = [];

        if (Utils.isNil(this.group)) {
            this.group = "default";
        }
    }




    remove(url: string, clear: boolean = false) {

    }

    async loadAssets() {
        if (!this.assets || this.assets.length <= 0) {
            return Promise.reject("assets is null");
        }

        return new Promise((resolve, reject) => {
            Laya.loader.load(this.assets, Laya.Handler.create(this, resolve));
        })
    }

    loadImg(url: string) {
        this.add({ url: url, type: Laya.Loader.IMAGE, priority: this.priority, group: this.group });
        return this;
    }

    loadJson(url: string) {
        this.add({ url: url, type: Laya.Loader.JSON, priority: this.priority, group: this.group });
        return this;
    }

    loadAny(url: string) {
        this.add({ url: url, priority: this.priority, group: this.group });
        return this;
    }

    clera() {
        if (this.assets.length <= 0) return;

        Laya.Loader.clearResByGroup(this.group);

        this.assets.length = 0;
    }

    private add(url: Laya.ILoadURL | Laya.ILoadURL[]) {
        if (Array.isArray(url)) {
            for (let item of url) {
                this.pushAss(item);
            }
        } else {
            this.pushAss(url);
        }

        return this;
    }

    private pushAss(c: Laya.ILoadURL) {
        let b = this.assets.some(v => v.url == c.url);
        if (b) return;

        this.assets.push(c);
    }
}

